import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { User, LoginForm } from '@/types'
import request from '@/utils/request'

export const useUserStore = defineStore('user', () => {
  const currentUser = ref<User | null>(null)
  const token = ref<string | null>(null)

  const login = async (form: LoginForm) => {
    const res = await request.post('/auth/login', form)
    token.value = res.token
    currentUser.value = res.user
    localStorage.setItem('token', res.token)
  }

  const logout = () => {
    token.value = null
    currentUser.value = null
    localStorage.removeItem('token')
  }

  const getUserInfo = async () => {
    const res = await request.get('/auth/user')
    currentUser.value = res
  }

  return {
    currentUser,
    token,
    login,
    logout,
    getUserInfo
  }
}) 